# !/usr/bin/python
# -*- coding: UTF-8 -*-
#https://github.com/IanHarvey/bluepy/blob/master/bluepy

import os
import sys
import shutil
import datetime
import binascii
import bluepy
from time import ctime,sleep
#from bluepy.btle import Scanner, DefaultDelegate, Peripheral

class ScanDelegate(bluepy.btle.DefaultDelegate):

    def __init__(self,whitelist,save2file = False,scandev = True,scandata = True):
        bluepy.btle.DefaultDelegate.__init__(self)
        self.whitelist = whitelist
        self.save2file = save2file 
        self.scandev = scandev 
        self.scandata = scandata

    def handleNotification(self, cHandle, data):
        data = binascii.b2a_hex(data)
        print("Notification:", str(cHandle), " data ", data)

    def handleDiscovery(self, dev, isNewDev, isNewData):
        if self.scandev:
            #if isNewDev:
            print "Discovered device:", dev.addr,dev.scanData.get(8,"No name")
        if self.scandata:
            if isNewDev:
                pass 
            else:#elif isNewData:
                if (len(self.whitelist) == 0) or (dev.addr.upper() in (item.upper() for item in self.whitelist)):
                    if self.save2file:
                        fo = open("../logdata/" + dev.addr.upper().replace(":","_",5)+".txt", "ab")
                        #写入文件时间戳
                        fo.write("time %s " % datetime.datetime.now())
                        #写入文件MAC
                        fo.write("mac %s " % dev.addr)
                        #写入文件信号强度
                        fo.write("rssi %d " % dev.rssi)
                        #写入数据
                        fo.write("data ")

                    print "Received new data from mac", dev.addr.upper(),"time",datetime.datetime.now(),"rssi %d" % dev.rssi,"data",

                    #for i in map(ord,(dev.scanData[255])):#此处只打印自定义数据
                    #    print "%02X " % i,
                    #    if self.save2file: 
                    #        fo.write("%02X " % i)

                    for keys in dev.scanData:
                        print "%02X %02X" % (1+len(dev.scanData[keys]),int(keys)),
                        if self.save2file: 
                            fo.write("%02X %02X" % (1+len(dev.scanData[keys]),int(keys)))
                        for i in map(ord,dev.scanData[keys]):
                            print "%02X" % (i),
                            if self.save2file: 
                                fo.write("%02X" % i)

                    print ""
                    if self.save2file:
                        fo.write("\r\n")
                        fo.close()
                    #return scandata;

def lescan(hcix,timeout, delegate):
    scanner = bluepy.btle.Scanner(hcix).withDelegate(delegate)
    devices = scanner.scan(timeout)
    return devices;

#def ledump(devices,whitelist):
#    for dev in devices:
#        print "Device %s (%s), RSSI=%d dB" % (dev.addr, dev.addrType, dev.rssi)
#        for (adtype, desc, value) in dev.getScanData():
#            print "  %s = %s" % (desc, value)
#    return;

lecon = None
def leconnect2mac(addr,mactype):
    global lecon
    if not addr is None and lecon is None:
        #print "connecting to",addr
        lecon = bluepy.btle.Peripheral(addr,mactype)
        lecon.setDelegate(ScanDelegate(addr,False,True,True))
        lecon.services = lecon.discoverServices().values()
        #print "connected"
    return lecon;


def printusage():
    print "Usage:"
    print "     sudo lescan.py lescan/ledump/lecon2mac [-h help] [-i hci dev number] [-s Save a file and Remarks] [-t timeout] [-w/-wf whitelist:..../whitelist in file]"
    print "     sudo python lescan.py ledump -i hci0 -s 10_00_no -t 6 -wf ./whitelist.txt"
    return;


if __name__ == '__main__':

    if "-h" in sys.argv:
        printusage()  
        exit()
    if "-t" in sys.argv:
        timeout = int(sys.argv[sys.argv.index("-t") + 1])  
    else:
        timeout = 0      
    if "-w" in sys.argv:
        whitelist = sys.argv[(sys.argv.index("-w") + 1):len(sys.argv)]
    elif "-wf" in sys.argv:
        if (sys.argv.index("-wf") + 1) < len(sys.argv):
            whitelist = []
            testconditionlist = []
            fs = open(sys.argv[(sys.argv.index("-wf") + 1)],"rb")
            lines = fs.readlines()
            fs.close()
            for i in lines:
                if len(i.split()) > 0 and i.split()[0] == '-w':
                    whitelist.append(i.split()[1].upper())
                if len(i.split()) > 2 and i.split()[2] == '-s':
                    testconditionlist.append(i.split()[3].upper())   
            #print whitelist,testconditionlist
        else:
            print "\r\nplese input the whitelist file path\r\n"
            exit() 
        #exit()  
    else:
        whitelist = []  
    if "-i" in sys.argv:
        hcix = int(sys.argv[sys.argv.index("-i") + 1][3:])
    else:
        hcix = 0

    if "-s" in sys.argv:
        saveafile = True
        #删除旧数据文件
        for filename in whitelist:
            filename = "../logdata/" + filename.lower().replace(":","_",5) + ".txt"
            if os.path.exists(filename):
                os.remove(filename)
        #创建新的数据文件
        i = 0
        if not os.path.exists(r'../logdata/'):
            os.makedirs(r'../logdata/')
        for filename in whitelist:
            fo = open("../logdata/" + filename.lower().replace(":","_",5) + ".txt","wb")
            if "-wf" in sys.argv and len(testconditionlist) == len(whitelist):
                fo.write("# power %s\r\n# dist %s\r\n# occl %s\r\n# mac %s\r\n# start_time %s\r\n" % 
                        (testconditionlist[i].split('_')[0],
                         testconditionlist[i].split('_')[1],
                         testconditionlist[i].split('_')[2],# no ,half ,full
                         filename.lower(),
                         datetime.datetime.now()
                         ))
            else:
                fo.write("# power %s\r\n# dist %s\r\n# occl %s\r\n# mac %s\r\n# start_time %s\r\n" % 
                        (sys.argv[(sys.argv.index("-s") + 1)].split('_')[0],
                         sys.argv[(sys.argv.index("-s") + 1)].split('_')[1],
                         sys.argv[(sys.argv.index("-s") + 1)].split('_')[2],# no ,half ,full
                         filename.lower(),
                         datetime.datetime.now()
                         ))
            fo.close()
            i += 1
    else:
        saveafile = False
    #开始扫描
    print "Test start: %s" % datetime.datetime.now()
    
    if "lescan" in sys.argv:
        lescan(hcix,timeout,ScanDelegate(whitelist,saveafile,True,False))
    
    if "ledump" in sys.argv:
        lescan(hcix,timeout,ScanDelegate(whitelist,saveafile,False,True))
        
    if "lecon2mac" in sys.argv:
        if len(whitelist):
            conn=leconnect2mac(whitelist[0],"public")#"random"
            try:
                for svc in conn.services:
                    print(str(svc), ":")
                    for ch in svc.getCharacteristics():
                        print("    {}, hnd={}, supports {}".format(ch, hex(ch.handle), ch.propertiesToString()))
                        chName = bluepy.btle.AssignedNumbers.getCommonName(ch.uuid)
                        if (ch.supportsRead()):
                            try:
                                print("    ->", repr(ch.read()))
                            except BTLEException as e:
                                print("    ->", e)
            finally:
                conn.disconnect()

    if saveafile == True: 		
		for filename in whitelist:
			fo = open("../logdata/" + filename.lower().replace(":","_",5) + ".txt","ab")
			fo.write("# stop_time %s\r\n" % datetime.datetime.now())
			fo.close()
	
    if os.path.exists(r'../logdata/'):
        if os.path.exists('../' + sys.argv[(sys.argv.index("-s") + 1)]):
            shutil.rmtree('../' + sys.argv[(sys.argv.index("-s") + 1)])
        os.rename(r'../logdata/','../' + sys.argv[(sys.argv.index("-s") + 1)])
        os.system('sudo chmod -R 777 ' + '../' + sys.argv[(sys.argv.index("-s") + 1)])
    print "Test over: %s" % datetime.datetime.now()#,sys.argv


   
